package net.hzlj.platform.enterprise.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.readystatesoftware.systembartint.SystemBarTintManager;

import net.hzlj.platform.enterprise.AppManager;
import net.hzlj.platform.enterprise.BootApp;
import net.hzlj.platform.enterprise.common.EventBusParameter;
import net.hzlj.rl.zhangjiajie.R;
import net.hzlj.platform.enterprise.common.Constant;
import net.hzlj.platform.enterprise.common.WeakReferenceHandler;
import net.hzlj.platform.enterprise.task.Task;
import net.hzlj.platform.enterprise.task.TaskListener;
import net.hzlj.platform.enterprise.utils.SystemUtils;
import net.hzlj.platform.enterprise.widght.LoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;

import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpCycleContext;
import cn.finalteam.okhttpfinal.HttpTaskHandler;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * @ClassName: BaseActivity
 * @Description: BaseActivity 基类Activity
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-7-25 06:57:14
 */
@RuntimePermissions
public abstract class BaseActivity extends AppCompatActivity implements HttpCycleContext,TaskListener {

    protected final String HTTP_TASK_KEY = "http_request_task_activity_key_" + hashCode();

    private MyHandler<BaseActivity> mHandler;
    private PermissionHandler mPermissionHandler;
    public ViewGroup mDecorView;

    public boolean mHasNextPage = false;//是否有分页

    public boolean mIsLoading = false;//当前数据是否在加载

    public boolean mIsStart = true;//是否是第一次调用接口

    protected boolean mIsHiddenStatusBar  = false;

    public int mCurrentIndex = 0;//当前页码

    public LoadingDialog mLoadingDialog;

    abstract void handleMessage(BaseActivity activity, Message msg);

    static class MyHandler<T> extends WeakReferenceHandler<T> {

        public MyHandler(T reference) {
            super(reference);
        }

        @Override
        protected void handleMessage(T reference, Message msg) {
            BaseActivity activity = (BaseActivity) reference;
            activity.handleMessage(activity, msg);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRootView();
        initSystemStatusBar();
        ButterKnife.bind(this);
//        this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
        AppManager.getAppManager().addActivity(this);
        /***
         * 1、onEvent ：如果使用onEvent作为订阅函数，那么该事件在哪个线程发布出来的，onEvent就会在这个线程中运行，也就是说发布事件和接收事件线程在同一个线程。使用这个方法时，在onEvent方法中不能执行耗时操作，如果执行耗时操作容易导致事件分发延迟。
         * 2、onEventMainThread ：如果使用onEventMainThread作为订阅函数，那么不论事件是在哪个线程中发布出来的，onEventMainThread都会在UI线程中执行，接收事件就会在UI线程中运行，这个在Android中是非常有用的，因为在Android中只能在UI线程中跟新UI，所以在onEvnetMainThread方法中是不能执行耗时操作的。
         * 3、onEventBackgroundThread ：如果使用onEventBackgrond作为订阅函数，那么如果事件是在UI线程中发布出来的，那么onEventBackground就会在子线程中运行，如果事件本来就是子线程中发布出来的，那么onEventBackground函数直接在该子线程中执行。
         * 4、onEventAsync：使用这个函数作为订阅函数，那么无论事件在哪个线程发布，都会创建新的子线程在执行onEventAsync.
         *
         * 5、MAIN UI主线程
         *6、BACKGROUND 后台线程
         *7、POSTING 和发布者处在同一个线程
         *8、ASYNC 异步线程
         */
        EventBus.getDefault().register(this);
        initStrictMode();
        getDeviceDensity();
        initTitleBar();
        initLoadingDialog();
        initWidget();
        initData();
    }

    private void initSystemStatusBar(){
        if (mIsHiddenStatusBar){
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            //setTranslucentStatus(true);
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        // 激活状态栏
        tintManager.setStatusBarTintEnabled(true);
        // enable navigation bar tint 激活导航栏
        tintManager.setNavigationBarTintEnabled(true);
        //设置系统栏设置颜色
        //tintManager.setTintColor(R.color.red);
        //给状态栏设置颜色
        tintManager.setStatusBarTintResource(R.color.status_bar_bg);
        //Apply the specified drawable or color resource to the system navigation bar.
        //给导航栏设置资源
        tintManager.setNavigationBarTintResource(R.color.status_bar_bg);
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEventBackground(EventBusParameter parameter) {
        onEventRunBackground(parameter);
    }

    protected void onEventRunBackground(EventBusParameter parameter) {

    }

    /**
     * 获取当前设备的屏幕密度等基本参数
     */
    protected void getDeviceDensity() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        Constant.DENSITY = metrics.density;
        Constant.EXACT_SCREEN_HEIGHT = metrics.heightPixels;
        Constant.EXACT_SCREEN_WIDTH = metrics.widthPixels;
    }


    private void initStrictMode(){
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .penaltyDialog()
                    .detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
    }



    protected void setRootView(){
    }

    //初始化标题栏
    protected void initTitleBar(){
        mHandler = new MyHandler<BaseActivity>(this);
    }

    //初始化控件
    protected void initWidget() {

    }

    //初始化数据
    protected void initData() {

    }

    //初始化等待框
    protected void initLoadingDialog() {
        mLoadingDialog = new LoadingDialog(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
        HttpTaskHandler.getInstance().removeTask(HTTP_TASK_KEY);
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public String getHttpTaskKey() {
        return HTTP_TASK_KEY;
    }

    @Override
    public void onTaskResult(Task task) {
    }

    /***
     * 权限回调接口
     */
    public abstract class PermissionHandler{

        //权限通过
        public abstract void onGranted();

        //权限拒绝
        public void onDenied(){

        }
    }

    /**
     * 请求相机权限
     * @param permissionHandler
     */
    protected void requestCameraPermission(PermissionHandler permissionHandler) {
        this.mPermissionHandler = permissionHandler;
        BaseActivityPermissionsDispatcher.handleCameraPermissionWithCheck(this);
    }

    /**
     * 相机权限通过
     */
    @NeedsPermission({
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA})
    void handleCameraPermission() {
        // NOTE: Perform action that requires the permission. If this is run by PermissionsDispatcher, the permission will have been granted
        if (mPermissionHandler != null){
            mPermissionHandler.onGranted();
        }
    }

    /***
     * 相机权限拒绝
     */
    @OnPermissionDenied({
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA})
    void deniedCameraPermission() {
        if (mPermissionHandler != null){
            mPermissionHandler.onDenied();
        }
    }

    @OnNeverAskAgain({
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA})
    void OnCameraNeverAskAgain() {
        showDialog("[相机，电话，存储，位置，麦克风]");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        BaseActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    public void showDialog(String permission) {
        new AlertDialog.Builder(this)
                .setTitle("权限申请")
                .setMessage("在设置-应用-" + getString(R.string.app_name) + "-权限中开启" + permission + "权限，以正常使用")
                .setPositiveButton("开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivity(intent);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mPermissionHandler != null){
                            mPermissionHandler.onDenied();
                        }
                        dialog.dismiss();
                    }
                })
                .setCancelable(false)
                .show();
    }

    public boolean selfPermissionGranted(String permission) {
        // For Android < Android M, self permissions are always granted.
        boolean result = true;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (SystemUtils.getTargetSdkVersion(this) >= Build.VERSION_CODES.M) {
                // targetSdkVersion >= Android M, we can
                // use Context#checkSelfPermission
                result = checkSelfPermission(permission)
                        == PackageManager.PERMISSION_GRANTED;
            } else {
                // targetSdkVersion < Android M, we have to use PermissionChecker
                result = PermissionChecker.checkSelfPermission(this, permission)
                        == PermissionChecker.PERMISSION_GRANTED;
            }
        }
        return result;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //检查用户是否登录，如果没有登录，
        if (LoginActivity.LOGIN_ACTIVITY == null){
            if (!BootApp.getInstance().isLogin()){
                Toast.makeText(this,"请预先登录,应用将在3秒后自动退出",Toast.LENGTH_LONG).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        BootApp.getInstance().exitLogin();
                        System.exit(0);
                    }
                },3000L);
            }

        }
    }
}
